package com.zhf.testBatch;

import com.zhf.utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/9/24 23:26
 */
public class BatchInsert {

    public static void main(String[] args) throws SQLException {
        //使用批处理向表中添加10000条数据
        //获取连接
        Connection connection = DruidUtils.getConnection();

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement("insert into testBatch(uname) values(?)");

        //执行批量插入操作
        for (int i=0;i<10000;i++){
            preparedStatement.setString(1,"小强"+i);

            //将SQL添加到批处理列表
            preparedStatement.addBatch();
        }

        //添加时间戳测试执行效率
        long start = System.currentTimeMillis();

        //执行批处理
        preparedStatement.executeBatch();

        long end = System.currentTimeMillis();

        System.out.println("执行时间："+(end-start)+"ms");


        //释放资源
        DruidUtils.close(connection,preparedStatement);

    }
}
